package com.wjw.java.collection.set_;

import java.util.LinkedHashSet;
import java.util.Objects;
import java.util.Set;

/**
 * LinkedHashSet练习:
 * 定义一个Car类,属性有name,age
 * 创建3个User对象,放入Hashset中
 * 当name和price的值相同时,认为是相同汽车,不能放入LinkedHashSet中
 */
public class Exercise_LinkedHashSet {
    public static void main(String[] args) {
        Set<Car> set = new LinkedHashSet<>();
        set.add(new Car("奥迪",300000.99));
        set.add(new Car("奥迪",300000.99));
        set.add(new Car("宝马",350000.99));
        set.add(new Car("奔驰",350000.99));
        System.out.println(set);
    }
}
//重写hashcode和equals,当name和price的值相同时hashcode值相同
class Car{
    private String name;
    private Double price;

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getPrice() {
        return this.price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public Car() {}

    public Car(String name, Double price) {
        this.name = name;
        this.price = price;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || this.getClass() != o.getClass()) return false;
        Car car = (Car) o;
        return Objects.equals(this.name, car.name) &&
                Objects.equals(this.price, car.price);
    }

    @Override
    public int hashCode() {
        return Objects.hash(this.name, this.price);
    }

    @Override
    public String toString() {
        return "Car{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
}